/*
 * (C) Copyright 2006-2010 Nuxeo SAS (http://nuxeo.com/) and contributors.
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Lesser General Public License
 * (LGPL) version 2.1 which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/lgpl.html
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * Contributors:
 *     bstefanescu
 */
package org.nuxeo.gwt.habyt.app.client.js;

import org.nuxeo.gwt.habyt.invocation.client.events.EventBus;

import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.event.shared.HandlerRegistration;

/**
 * A Java overlay type over a JS native type.
 * 
 * This native type is the one used to propagate configuration and events from
 * JS code to java code.
 * 
 * 
 * @author <a href="mailto:bs@nuxeo.com">Bogdan Stefanescu</a>
 * 
 */
public class JsBridge {

    private static JsBridge instance;

    public native static void install()/*-{
                                       if ($wnd.g === undefined) {
                                       $wnd.g = {}; 
                                       }
                                       $wnd.g.fire = function (eventId, target, data) {
                                       return @org.nuxeo.gwt.habyt.app.client.js.JsBridge::handleEvent(Ljava/lang/String;Ljava/lang/String;Lcom/google/gwt/core/client/JavaScriptObject;)(eventId, target, data); 
                                       };
                                       }-*/;

    static void handleEvent(String name, String target, JavaScriptObject data) {
        JsEvent event = new JsEvent(name, target, data != null ? new JsObject(
                data) : null);
        EventBus.get().fireEvent(event);
    }

    public static HandlerRegistration addHandler(JsEventHandler handler) {
        return EventBus.get().addHandler(JsEvent.getType(), handler);
    }

}
